<template>
  <div class="merchant-page">
    <!-- 详情页视图 -->
    <el-card v-if="viewMode === 'detail'" class="page-card">
      <div slot="header" class="card-header">
        <span>商家详情</span>
        <el-button
            type="primary"
            size="small"
            @click="switchToEdit"
            class="edit-btn"
        >
          编辑
        </el-button>
      </div>

      <el-descriptions column="1" border>
        <el-descriptions-item label="商家ID">{{ merchant.id }}</el-descriptions-item>
        <el-descriptions-item label="商家账号">{{ merchant.username }}</el-descriptions-item>
        <el-descriptions-item label="商户名">{{ merchant.name }}</el-descriptions-item>
        <el-descriptions-item label="商家照片">
          <el-image
              v-if="merchant.image"
              :src="merchant.image"
              style="width: 200px; height: 150px; object-fit: contain"
              :preview-src-list="[merchant.image]"
          ></el-image>
          <span v-else>无照片</span>
        </el-descriptions-item>
        <el-descriptions-item label="手机号">{{ merchant.phone }}</el-descriptions-item>
        <el-descriptions-item label="商家描述">{{ merchant.intro || '无描述' }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 编辑页视图 -->
    <el-card v-if="viewMode === 'edit'" class="page-card">
      <div slot="header" class="card-header">
        <span>编辑商家</span>
        <div class="button-group">
          <el-button
              size="small"
              @click="switchToDetail"
          >
            取消
          </el-button>
          <el-button
              type="primary"
              size="small"
              @click="saveMerchant"
          >
            保存
          </el-button>
        </div>
      </div>

      <el-form
          ref="merchantForm"
          :model="formData"
          :rules="formRules"
          label-width="120px"
          class="merchant-form"
      >
        <el-form-item label="商家ID" prop="id">
          <el-input v-model="formData.id" disabled></el-input>
        </el-form-item>

        <el-form-item label="商家账号" prop="username">
          <el-input v-model="formData.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="商户名" prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>

        <el-form-item label="商家照片" prop="image">
          <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :show-file-list="false"
              :on-success="handleImageUpload"
              :before-upload="beforeImageUpload"
          >
            <el-image
                v-if="formData.image"
                :src="formData.image"
                style="width: 200px; height: 150px; object-fit: contain"
            ></el-image>
            <div v-else class="upload-placeholder">
              <el-icon><Plus /></el-icon>
              <div class="upload-text">点击上传</div>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>

        <el-form-item label="商家描述" prop="intro">
          <el-input
              v-model="formData.intro"
              type="textarea"
              rows="4"
              placeholder="请输入商家描述"
          ></el-input>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import {useRoute}   from "vue-router";
import server from "../utils/request.js";

// 视图模式：detail-详情页，edit-编辑页
const viewMode = ref('detail')
const id = useRoute().query.id
// 商家数据
const merchant = ref({
  id: '',
  username: '',
  name: '',
  image: '',
  phone: '',
  intro: '',
  status: 1
})

// 表单数据
const formData = reactive({
  id: '',
  username: '',
  name: '',
  image: '',
  phone: '',
  intro: '',
  status: 1
})

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入商户名', trigger: 'blur' },
    { min: 2, max: 50, message: '商户名长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  intro: [
    { max: 500, message: '商家描述不能超过500个字符', trigger: 'blur' }
  ]
})

// 上传相关配置
const uploadUrl = 'http://localhost:8080/merchant/upload' // 实际项目中替换为真实上传接口

// 切换到编辑模式
const switchToEdit = () => {
  // 复制当前数据到表单
  Object.assign(formData, JSON.parse(JSON.stringify(merchant.value)))
  viewMode.value = 'edit'
}

// 切换到详情模式
const switchToDetail = () => {
  viewMode.value = 'detail'
}
// 这里使用了表单验证，实际项目中需要根据需要调整
const merchantForm = ref(null)
// 保存商家信息
const saveMerchant = async () => {
  if (!merchantForm.value) {
    ElMessage.error('表单实例未找到');
    return;
  }

  try {
    // 调用表单验证（Promise 形式）
    await merchantForm.value.validate();

    // 验证通过后提交
    const { data } = await server.put(`/merchant/`, formData);
    if (data.code === 200) {
      merchant.value = { ...formData };
      viewMode.value = 'detail';
      ElMessage.success('保存成功');
    } else {
      ElMessage.error(`保存失败：${data.msg}`);
    }
  } catch (error) {
    // 验证失败会进入这里（无需额外处理，表单会自动提示错误）
    console.log('表单验证失败', error);
  }
};

// 图片上传成功处理
const handleImageUpload = (response) => {
  console.log(response)
  // 假设上传接口返回格式为 { url: '图片地址' }
  formData.image = response.data
  console.log(formData.image)
  ElMessage.success('图片上传成功')
}

// 图片上传前验证
const beforeImageUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJpgOrPng) {
    ElMessage.error('只能上传JPG/PNG格式的图片')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB')
    return false
  }
  return true
}

// 模拟获取商家详情数据
const fetchMerchantDetail = async () => {
  try {
    let {data:data} = await server.get(`merchant/${id}`)
    Object.assign(merchant.value,data.data)
  } catch (error) {
    ElMessage.error('获取商家详情失败')
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchMerchantDetail()
})
</script>

<style scoped>
.merchant-page {
  padding: 20px;
}

.page-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.edit-btn {
  margin-left: auto;
}

.button-group {
  display: flex;
  gap: 10px;
}

.merchant-form {
  margin-top: 20px;
}

.avatar-uploader {
  display: inline-block;
}

.upload-placeholder {
  width: 200px;
  height: 150px;
  border: 1px dashed #ccc;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.upload-text {
  margin-top: 8px;
  color: #666;
  font-size: 14px;
}
</style>